package com.wld.vertx;

import com.alibaba.fastjson.JSONObject;
import com.wld.vertx.config.VertxConfig;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.WebSocketFrame;
import io.vertx.core.json.JsonObject;

import java.util.Map;
import java.util.Objects;

public class ConsumerHttpServerVerticle extends AbstractVerticle {
    private long timerID;
    private HttpClient client = null;
    private Boolean isConnection = false;

    public void start() {
        System.out.println("ConsumerHttpServerVerticle start");
        initHttpClient();

        //尝试重连
        vertx.setPeriodic(5000, id -> {
            if (!isConnection) {
                initHttpClient();
            }
        });
    }

    private void initHttpClient() {
        if (Objects.nonNull(client)) {
            client.close();
            client = null;
        }
        client = vertx.createHttpClient();
        websocketHandler();
    }

    private void websocketHandler() {
        client.websocket(VertxConfig.PORT, VertxConfig.IP, VertxConfig.THIRD_PARTY_URI_PATH, ws -> {
            System.out.println("服务器连接成功。");
            System.out.println("ws: " + ws.textHandlerID());
            isConnection = true;
            //发送心跳
            JsonObject pingMsg = new JsonObject().put("type", "ping");
            ws.writeFrame(WebSocketFrame.textFrame(pingMsg.encode(), true));

            timerID = vertx.setPeriodic(5000, id -> {
                ws.writeFrame(WebSocketFrame.textFrame(pingMsg.encode(), true));
            });

            //发送需要订阅数据的地址，仅支持文档中的订阅地址: equipment.realTimeData、equipment.healthStatus、equipment.alarm
            JsonObject registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.REAL_TIME_DATA_ADDRESS);
            ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
           registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.HEALTH_STATUS_ADDRESS);
           
           ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));
           
            registerDataMsg = new JsonObject().put("type", "register").put("address", VertxConfig.ALARM_ADDRESS);
            ws.writeFrame(WebSocketFrame.textFrame(registerDataMsg.encode(), true));

            ws.handler(buffer -> {
                //接受到的订阅地址的数据
                Map receiveData = JSONObject.parseObject(buffer.toString(), Map.class);
                System.out.println("receiveData: " + receiveData.get("body"));
            });

            ws.closeHandler(close -> {
                //连接关闭的处理
                isConnection = false;
                vertx.cancelTimer(timerID);
            });
        }, wsErr -> {
            //连接失败，需要做的处理
            System.out.println("服务器连接失败，原因：" + wsErr.getMessage() + "，时间：" + System.currentTimeMillis());
            isConnection = false;
            vertx.cancelTimer(timerID);
        });
    }


}
